package com.example.boot.modules.auth.component;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 王令
 * @since 2022/12/1 21:41
 */
public class WeixinLoginTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "wx_login";
    private final AuthenticationManager authenticationManager;

    public WeixinLoginTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
    }

    protected WeixinLoginTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        final Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        final String phone = parameters.get("phone");
        final String js_code = parameters.get("js_code");
        parameters.remove("js_code");
        Authentication userAuth = new WeixinLoginAuthenticationToken(phone, js_code);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);

        userAuth = authenticationManager.authenticate(userAuth);

        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate mobile: " + js_code);
        }

        final OAuth2Request storedOAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
